package com.jus.player.fragment.main;

import static com.jus.player.config.AppConfig.INT_1;
import static com.jus.player.config.AppConfig.INT_2;

import android.os.Handler;
import android.os.Looper;

import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.google.android.material.tabs.TabLayout;
import com.jus.player.R;
import com.jus.player.adapter.HomeAdapter;
import com.jus.player.fragment.BaseFragment;
import com.jus.player.util.Tag;
import com.jus.player.util.cache.ProxyVideoCacheManager;

import java.util.ArrayList;
import java.util.List;

import xyz.doikki.videoplayer.player.VideoView;

/**
 * 首页
 */
public class HomeFragment extends BaseFragment {

    /**
     * 暂停播放的Tag
     */
    private String pauseTag;
    private ViewPager viewPager;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initView() {

        viewPager = findViewById(R.id.view_pager);

        List<String> titles = new ArrayList<>();
        titles.add(getString(R.string.str_follow));
        titles.add(getString(R.string.str_hot));
        titles.add(getString(R.string.str_recommend));
        viewPager.setAdapter(new HomeAdapter(getChildFragmentManager(), titles));
        viewPager.setCurrentItem(INT_2);

        TabLayout tabLayout = findViewById(R.id.tab_layout);
        tabLayout.setupWithViewPager(viewPager);
    }

    @Override
    protected void initData() {
        super.onDetach();
        getVideoViewManager().releaseByTag(Tag.HOT);
        getVideoViewManager().releaseByTag(Tag.RECOMMEND);
    }

    @Override
    public void onPause() {
        super.onPause();
        String tag;
        switch (viewPager.getCurrentItem()) {
            case INT_1:
                tag = Tag.HOT;
                break;
            case INT_2:
                tag = Tag.RECOMMEND;
                break;
            default:
                return;
        }
        VideoView videoView = getVideoViewManager().get(tag);
        pauseVideo(videoView, tag);
    }

    private final Handler pauseHandler = new Handler(Looper.getMainLooper());
    private Runnable pauseRunnable;
    private int retryCount = 0;
    private static final int MAX_RETRY = 20; // 最大重试次数

    private void pauseVideo(VideoView videoView, String tag) {
        // 清理之前的任务
        if (pauseRunnable != null) {
            pauseHandler.removeCallbacks(pauseRunnable);
        }
        if (!isAdded() || isDetached() || getActivity() == null || getActivity().isFinishing()) {
            return;
        }
        if (videoView != null && (videoView.getCurrentPlayState() == VideoView.STATE_PAUSED
                || videoView.getCurrentPlayState() == VideoView.STATE_IDLE)) {
            retryCount = 0;
            return;
        }
        if (videoView != null) {
            pauseTag = tag;
            videoView.pause();
        } else {
            videoView = getVideoViewManager().get(tag);
        }
        // 增加重试机制 缩短延迟时间但增加重试
        // 设置延迟检查
        VideoView finalVideoView = videoView;
        pauseRunnable = () -> {
            if (retryCount++ < MAX_RETRY) {
                pauseVideo(finalVideoView, tag);
            } else {
                retryCount = 0; // 达到最大重试次数后重置
            }
        };
        pauseHandler.postDelayed(pauseRunnable, 500);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (this.isHidden()) {
            return;
        }
        if (viewPager.getCurrentItem() == INT_1 && Tag.HOT.equals(pauseTag)) {
            getVideoViewManager().get(Tag.HOT).resume();
        }
        if (viewPager.getCurrentItem() == INT_2 && Tag.RECOMMEND.equals(pauseTag)) {
            getVideoViewManager().get(Tag.RECOMMEND).resume();
        }
        pauseTag = null;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            onPause();
        } else {
            onResume();
        }
    }

    @Override
    public void onDestroy() {
        // 清理Handler防止内存泄漏
        if (pauseRunnable != null) {
            pauseHandler.removeCallbacks(pauseRunnable);
        }
        super.onDestroy();
        ProxyVideoCacheManager.clearAllCache(getContext());
        Glide.get(requireContext()).clearMemory();
    }
}